package WebFinder

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/QRCode"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Slice"
	"gitee.com/fierce_wolf/go-web-crawler/WebCrawler"
	"github.com/PuerkitoBio/goquery"
	"regexp"
)

type WebChat struct {
	List []*WebCrawler.WebElement // 微信二维码的图片链接，其中text字段被识别为二维码的URL
}

func (e *WebChat) GetList() []*WebCrawler.WebElement {
	return e.List
}

func (e *WebChat) Find(els []*WebCrawler.WebElement) []*WebCrawler.WebElement {
	e.List = make([]*WebCrawler.WebElement, 0)

	// 找找符合特征的项目
	originals := make([]*WebCrawler.WebElement, 0)
	keywords := make([]string, 0)
	keywords = append(keywords, "微信")
	keywords = append(keywords, "WeChat")
	for _, keyword := range keywords {
		reg := regexp.MustCompile(keyword)
		els = WebCrawler.Site.FindElements(els, WebCrawler.Filter{
			Mode:  WebCrawler.ModeRegexp,
			Param: reg,
		})
		originals = Slice.Append(originals, els)
	}

	// 查找微信的图片链接
	for _, el := range originals {
		el.Selection.Parent().Find("img").Each(func(i int, s *goquery.Selection) {
			src, exists := s.Attr("src")
			if !exists {
				return
			}

			e.List = append(e.List, &WebCrawler.WebElement{
				Tag:       "img",
				Selection: s,
				Text:      src,
			})
		})
	}

	return originals
}

func (e *WebChat) Decode(host string) []*WebCrawler.WebElement {
	if len(e.List) == 0 {
		return nil
	}

	wxUrls := make([]*WebCrawler.WebElement, 0)
	for _, el := range e.List {
		// HTTP下载图片并解码二维码
		wxUrl, err := QRCode.DecodeHttpFile(WebCrawler.Http.MakeUrl(host, el.Text))
		if err != nil {
			continue
		}

		clone := el.Clone()
		clone.Text = wxUrl

		wxUrls = append(wxUrls, clone)
	}

	return wxUrls
}
